#include "widget.h"
#include "ui_widget.h"
#include "CityCodeUtils.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QMouseEvent>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPainter>
#include "Day.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //对窗口进行设置
    //this->setLayout(ui->verticalLayout_All);
    this->setFixedSize(520, 789);
    this->setWindowFlag(Qt::FramelessWindowHint);//创建无边框窗口，但会使得窗口无法移动

    //初始化
    menu = new QMenu(this);
    QAction *closeAct = new QAction(tr("退出"), this);
    closeAct->setIcon(QIcon(":/res/close.png"));
    menu->addAction(closeAct);
    //连接信号槽
    connect(closeAct, &QAction::triggered, this, [=](){
        this->close();
    });

    //由QNetworkAccessManager发起get请求
    manager = new QNetworkAccessManager(this);
    //指定请求的URL地址
    strUrl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=98146447&appsecret=5ZH72nGA";
    QUrl urlTianqi(strUrl);
    QNetworkRequest res(urlTianqi);
    reply = manager->get(res);

    //网络请求发起后进行数据读取
    connect(manager, &QNetworkAccessManager::finished, this, &Widget::readHttpReply);

    //让天气和图片路径对应起来
    weatherTypeMap.insert("小雪", ":/res/weather/xiaoxue.png");
    weatherTypeMap.insert("中雪", ":/res/weather/zhongxue.png");
    weatherTypeMap.insert("雨夹雪", ":/res/weather/yujiaxue.png");
    weatherTypeMap.insert("暴雪", ":/res/weather/baoxue.png");
    weatherTypeMap.insert("雨", ":/res/weather/yu.png");
    weatherTypeMap.insert("小雨", ":/res/weather/xiaoyu.png");
    weatherTypeMap.insert("阵雨", ":/res/weather/zhenyu.png");
    weatherTypeMap.insert("雷阵雨", ":/res/weather/leizhenyu.png");
    weatherTypeMap.insert("中雨", ":/res/weather/zhongyu.png");
    weatherTypeMap.insert("大雨", ":/res/weather/dayu.png");
    weatherTypeMap.insert("暴雨", ":/res/weather/baoyu.png");
    weatherTypeMap.insert("晴", ":/res/sun.png");
    weatherTypeMap.insert("多云", ":/res/weather/duoyun.png");
    weatherTypeMap.insert("阴", ":/res/weather/yin.png");
    weatherTypeMap.insert("雾", ":/res/weather/wu.png");
    weatherTypeMap.insert("霾", ":/res/weather/mai.png");
    weatherTypeMap.insert("扬沙", ":/res/weather/yangsha.png");
    weatherTypeMap.insert("沙尘暴", ":/res/weather/shachenbao.png");

    //初始化UI控件列表
    mWeekList << ui->label_Day_1 << ui->label_Day_2 << ui->label_Day_3
               << ui->label_Day_4 << ui->label_Day_5 << ui->label_Day_6;
    mDateList << ui->label_Date_1 << ui->label_Date_2 << ui->label_Date_3
               << ui->label_Date_4 << ui->label_Date_5 << ui->label_Date_6;
    mIconList << ui->label_WeatherIcon_1 << ui->label_WeatherIcon_2 << ui->label_WeatherIcon_3
              << ui->label_WeatherIcon_4 << ui->label_WeatherIcon_5 << ui->label_WeatherIcon_6;
    mWeaTypeList << ui->label_Weather_1 << ui->label_Weather_2  << ui->label_Weather_3
                   << ui->label_Weather_4  << ui->label_Weather_5  << ui->label_Weather_6;
    mAirList << ui->label_Airq_1 << ui->label_Airq_2  << ui->label_Airq_3
             << ui->label_Airq_4  << ui->label_Airq_5  << ui->label_Airq_6;
    mWDList << ui->label_WD_1 << ui->label_WD_2  << ui->label_WD_3
             << ui->label_WD_4  << ui->label_WD_5  << ui->label_WD_6;
    mWFList << ui->label_WF_1 << ui->label_WF_2  << ui->label_WF_3
             << ui->label_WF_4  << ui->label_WF_5  << ui->label_WF_6;

    //处理搜索回车操作
    connect(ui->lineEdit_City, &QLineEdit::returnPressed, this, [=](){
        ui->btn_Search->clicked();
    });

    //给控件安装事件过滤器
    ui->widget_7->installEventFilter(this);
    ui->widget_8->installEventFilter(this);
}

Widget::~Widget()
{
    delete ui;
}

//读取接收的内容
void Widget::readHttpReply(QNetworkReply *reply)
{
    //接收消息的状态码
    int resCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug() << "resCode = " << resCode;

    if(reply->error() == QNetworkReply::NoError && resCode == 200)
    {
        QByteArray data = reply->readAll();
        //服务器返回的字符编码格式是Utf8
        qDebug() << QString::fromUtf8(data);
        //解析json数据
        parseWeatherJsonDataNew(data);
    }
    else
    {
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败! " + QString(resCode));
        mes.setStyleSheet("QPushButton {color : red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}


//void Widget::parseWeatherJsonData(QByteArray rawData)
//{
//    //负责Json文档的解析函数
//    QJsonDocument jsonObj = QJsonDocument::fromJson(rawData);
//    //jsonObj不为空并且包含object键值对象
//    if(!jsonObj.isNull() && jsonObj.isObject())
//    {
//        //Json本身就是一个大的键值对
//        QJsonObject rootObj = jsonObj.object();

//        //开始提取信息
//        //1.提取日期
//        QString date = rootObj["date"].toString();
//        QString week = rootObj["week"].toString();
//        ui->label_Date->setText(date + " " + week);
//        //2.城市
//        QString city = rootObj["city"].toString();
//        ui->label_City->setText(city);
//        //3.当前温度与温度范围
//        QString currentTemp = rootObj["tem"].toString();
//        ui->label_CurrentTemp->setText(currentTemp + "℃");

//        ui->label_TempRange->setText(rootObj["tem2"].toString() + "℃" + "-"
//                + rootObj["tem1"].toString() + "℃");
//        //4.天气类型与图标
//        QString wea = rootObj["wea"].toString();
//        ui->label_Weather->setText(wea);
//        ui->label_WeatherIcon->setPixmap(weatherTypeMap[rootObj["wea"].toString()]);//label用setPixmap
//        //5.感冒指数
//        ui->label_GetCold->setText(rootObj["air_tips"].toString());
//        //6.风向 风力
//        ui->label_WD->setText(rootObj["win"].toString());
//        ui->label_WF->setText(rootObj["win_speed"].toString());
//        //7.PM2.5
//        ui->label_PMNum->setText(rootObj["air_pm25"].toString());
//        //8.湿度
//        ui->label_RHNum->setText(rootObj["humidity"].toString());
//        //9.空气质量
//        ui->label_AirLevel->setText(rootObj["air_level"].toString());
//    }
//}

//解析Json信息并存入自定义的类中
void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
   QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
   if(!jsonDoc.isNull() && jsonDoc.isObject())
   {
       QJsonObject jsonRoot = jsonDoc.object();
       days[0].mCity = jsonRoot["city"].toString();
       days[0].mPm25 = jsonRoot["aqi"].toObject()["pm25"].toString();
       if(jsonRoot.contains("data") && jsonRoot["data"].isArray())
       {
           QJsonArray weaArray = jsonRoot["data"].toArray();
           for(int i = 0; i < weaArray.size(); i++)
           {
               QJsonObject obj = weaArray[i].toObject();
               days[i].mDate = obj["date"].toString();
               days[i].mWeek = obj["week"].toString();
               days[i].mWeatherType = obj["wea"].toString();

               days[i].mTemp = obj["tem"].toString();
               days[i].mTempLow = obj["tem2"].toString();
               days[i].mTempHigh = obj["tem1"].toString();

               days[i].mWd = obj["win"].toArray()[0].toString();
               days[i].mWf = obj["win_speed"].toString();
               days[i].mAirq = obj["air_level"].toString();
               days[i].mHu = obj["humidity"].toString();
               days[i].mTips = obj["air_tips"].toString();
           }
       }
   }
   updateUi();
}

void Widget::updateUi()
{
    //把解析后的信息并更新到UI界面
    //1.日期
    ui->label_Date->setText(days[0].mDate + " " + days[0].mWeek);
    //2.城市
    ui->label_City->setText(days[0].mCity);
    //3.当前温度与温度范围
    ui->label_CurrentTemp->setText(days[0].mTemp + "℃");

    ui->label_TempRange->setText(days[0].mTempLow + "℃" + "-"
            + days[0].mTempHigh + "℃");
    //4.天气类型与图标
    ui->label_Weather->setText(days[0].mWeatherType);
    ui->label_WeatherIcon->setPixmap(weatherTypeMap[days[0].mWeatherType]);//label用setPixmap
    //5.感冒指数
    ui->label_GetCold->setText(days[0].mTips);
    //6.风向 风力
    ui->label_WD->setText(days[0].mWd);
    ui->label_WF->setText(days[0].mWf);
    //7.PM2.5
    ui->label_PMNum->setText(days[0].mPm25);
    //8.湿度
    ui->label_RHNum->setText(days[0].mHu);
    //9.空气质量
    ui->label_AirLevel->setText(days[0].mAirq);

    //更新下方界面的UI
    for(int i = 0; i < 6; i++)
    {
        if(i == 0)
        {
            mWeekList[i]->setText("今天");
        }
        else
        {
            mWeekList[i]->setText(days[i].mWeek);
        }

        //将日期进行分割，只取月份和日
        QStringList dayList = days[i].mDate.split("-");
        mDateList[i]->setText(dayList.at(1) + "/" + dayList.at(2));

        //将 多云转晴 切割并取出”晴“
        if(days[i].mWeatherType.contains("转"))
        {
            QStringList weaList = days[i].mWeatherType.split("转");
            mWeaTypeList[i]->setText(weaList.at(1));
            mIconList[i]->setPixmap(weatherTypeMap[weaList.at(1)]);
        }
        else
        {
            mWeaTypeList[i]->setText(days[i].mWeatherType);
            mIconList[i]->setPixmap(weatherTypeMap[days[i].mWeatherType]);
        }

        //不同的空气质量 label的背景颜色不同
        QString air = days[i].mAirq;
        mAirList[i]->setText(days[i].mAirq);
        if(air == "优")
        {
            mAirList[i]->setStyleSheet("color: rgb(230, 230, 230); background-color: rgb(32, 161, 98); border-radius:5px;");
        }
        else if(air == "良")
        {
            mAirList[i]->setStyleSheet("color: rgb(230, 230, 230); background-color: rgb(232, 176, 4); border-radius:5px;");
        }
        else if(air == "轻度污染")
        {
            mAirList[i]->setStyleSheet("color: rgb(230, 230, 230); background-color: rgb(255, 199, 199); border-radius:5px;");
        }
        else if(air == "中度污染")
        {
            mAirList[i]->setStyleSheet("color: rgb(230, 230, 230); background-color: rgb(155, 17, 17); border-radius:5px;");
        }
        else if(air == "严重污染")
        {
            mAirList[i]->setStyleSheet("color: rgb(230, 230, 230); background-color: rgb(120, 8, 8); border-radius:5px;");
        }

        mWDList[i]->setText(days[i].mWd);
        mWFList[i]->setText(days[i].mWf);
    }
}

//在特定的范围内去画曲线
bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->widget_7 && event->type() == QEvent::Paint)
    {
        drawHighTempLine();
        return true;
    }
    else if(watched == ui->widget_8 && event->type() == QEvent::Paint)
    {
        drawLowTempLine();
        return true;
    }
    return QWidget::eventFilter(watched, event);
}

void Widget::drawHighTempLine()
{
    //设置画笔
    QPainter painter(ui->widget_7);
    painter.setRenderHint(QPainter::Antialiasing, true);//抗锯齿
    painter.setPen(QColor(255, 170, 39));
    painter.setBrush(QColor(255, 170, 39));

    //计算平均温度并算出每天的温度和平均温度的差值
    int sum = 0;
    for(int i = 0; i < 6; i++)
    {
        sum += days[i].mTempHigh.toInt();
    }
    int ave = sum / 6;

    //开始画圆点
    QPoint points[6];
    for(int i = 0; i < 6; i++)
    {
        int off = 0;//记录差值
        points[i].setX(mAirList[i]->x() + mAirList[i]->width() / 2);
        off = days[i].mTempHigh.toInt() - ave;
        points[i].setY(ui->widget_7->height() / 2 - off * 2);
        painter.drawEllipse(QPoint(points[i]), 3, 3);
        //画出当天温度
        painter.drawText(points[i].x() - 15, points[i].y() - 5, days[i].mTempHigh + "℃");
    }

    //开始画线
    for (int i = 0; i < 5; i++)
    {
        painter.drawLine(points[i], points[i + 1]);
    }
}

void Widget::drawLowTempLine()
{
    //设置画笔
    QPainter painter(ui->widget_8);
    painter.setRenderHint(QPainter::Antialiasing, true);//抗锯齿
    painter.setPen(QColor(34, 162, 195));
    painter.setBrush(QColor(34, 162, 195));

    //计算平均温度并算出每天的温度和平均温度的差值
    int sum = 0;
    for(int i = 0; i < 6; i++)
    {
        sum += days[i].mTempLow.toInt();
    }
    int ave = sum / 6;

    //开始画圆点
    QPoint points[6];
    for(int i = 0; i < 6; i++)
    {
        int off = 0;//记录差值
        points[i].setX(mAirList[i]->x() + mAirList[i]->width() / 2);
        off = days[i].mTempLow.toInt() - ave;
        points[i].setY(ui->widget_7->height() / 2 - off * 3);
        painter.drawEllipse(QPoint(points[i]), 3, 3);
        //画出当天温度
        painter.drawText(points[i].x() - 15, points[i].y() - 5, days[i].mTempLow + "℃");
    }

    //开始画线
    for (int i = 0; i < 5; i++)
    {
        painter.drawLine(points[i], points[i + 1]);
    }
}

//鼠标点击触发的事件函数
void Widget::mousePressEvent(QMouseEvent *event)
{
    //右键退出功能
    if(event->button() == Qt::RightButton)
    {
        menu->exec(QCursor::pos());//让菜单在鼠标点击处展示
    }

    //左键移动窗口功能
    if(event->button() == Qt::LeftButton)
    {
        //需要获得 鼠标当前位置 窗口当前位置的相对偏移值
        mOffset = event->globalPos() - this->pos();
    }
}

//鼠标左键按下后的移动，导致这个事件被调用，计算出并且移动到窗口的新位置
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    //拖拽时 需要算出窗口的实时位置并且移动到这个位置 = event.globalpos() - moffset
    this->move(event->globalPos() - mOffset);
}

//QString Widget::getCItyCodeFromName(QString cityName)
//{
//    //打开Json文件
//    QFile file(":/res/citycode.json");
//    file.open(QIODevice::ReadOnly);
//    QByteArray rawData = file.readAll();
//    file.close();

//    //解析Json文件
//    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
//    if(jsonDoc.isArray())
//    {
//        QJsonArray cities = jsonDoc.array();
//        for(QJsonValue value : cities)
//        {
//            if(value.isObject())
//            {
//                QString Name = value["city_name"].toString();
//                if(cityName == Name)
//                {
//                    return value["city_code"].toString();
//                }
//            }
//        }
//        //对比完后都没发现对应的城市名字
//        return  " ";
//    }
//}

void Widget::on_btn_Search_clicked()
{
    QString cityName = ui->lineEdit_City->text();
    QString cityCode = cityCodeUtils.getCItyCodeFromName(cityName);
    if(cityCode != NULL)
    {
        //发起新的连接
        strUrl += "&cityid=" + cityCode;
        manager->get(QNetworkRequest(QUrl(strUrl)));
    }
    else
    {
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名! ");
        mes.setStyleSheet("QPushButton {color : red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}
